#! @BASH@
# -*- mode: sh -*-
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Written by Victor Ananjevsky, 2010
#

VERSION=@VERSION@
GETTEXT_DOMAIN=@PACKAGE@

FORMAT="%t"
SPACES=0
VERBOSE=0

function usage () {
    echo $"${0##*/}, version - $VERSION"
    echo $"  Rename files by tags"
    echo $"Usage: ${0##*/} [-hsv] [-f FORMAT] <filename> ..."
    echo $"   -f FORMAT        specify a format of a new name"
    echo $"   -s               replace spaces by _"
    echo $"   -V               verbose output"
    echo $"   -h               show this help"
    echo $"   -v               show version"
    echo
    echo $"Format substitutions:"
    echo $"   %a               Artist"
    echo $"   %A               Album"
    echo $"   %g               Genre"
    echo $"   %t               Title"
    echo $"   %T               Track"
    echo $"   %y               Year"
    echo $"Default format is '$FORMAT'"
}

# Parse command line
OPTIND=1
while getopts f:hsvV opt ; do
    case "$opt" in
        f) FORMAT=$OPTARG ;;
	s) SPACES=1 ;;
        V) VERBOSE=1 ;;
        h) usage ; exit 0 ;;
        v) echo $"${0##*/}, version - $VERSION" ; exit 0 ;;
    esac
done
shift $(($OPTIND - 1))
[[ "$1" == '--' ]] && shift

# main loop
for file 
do
    [[ $VERBOSE -eq 1 ]] && echo "proceed $file ..."
    eval $(mtag --utf --shell "$file")
    new_name=$(echo $FORMAT | sed "s/%a/$MTAG_ARTIST/;s/%A/$MTAG_ALBUM/;s/%g/$MTAG_GENRE/;s/%t/$MTAG_TITLE/;s/%T/$MTAG_TRACK/;s/%y/$MTAG_YEAR/")
    [[ $SPACES == 1 ]] && new_name=$(echo $new_name | sed "s/ /_/g")
    dir=$(dirname "$file")
    ext=${file##*.}
    new_dir=$(dirname "$new_name")
    [[ $new_dir ]] && mkdir -p "$dir/$new_dir"
    [[ "$file" != "$dir/$new_name.$ext" ]] && mv "$file" "$dir/$new_name.$ext"
done
